package my.dao.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.ClassUtils;

//@Configuration
//@EnableTransactionManagement
public class SysDataSourceConfiguration {
    @Autowired
    ApplicationContext applicationContext;


    public static final String DATASOURCE_NAME = "sysDataSource";
    /**
     * 系统数据库,保存系统相关的数据.
     */
    @Bean(DATASOURCE_NAME)
    @ConditionalOnMissingBean
    @ConfigurationProperties(prefix = "spring.datasource.sys")
    public DataSource sysDataSource() {
        final String[] DATA_SOURCE_TYPE_NAMES = new String[] {
            "com.alibaba.druid.pool.DruidDataSource",
            "org.apache.tomcat.jdbc.pool.DataSource",
            "org.apache.commons.dbcp2.BasicDataSource" };
        return new DataSourceBuilder(applicationContext.getClassLoader()) {
            @Override
            @SuppressWarnings("unchecked")
            public Class<? extends DataSource> findType() {
                for (String name : DATA_SOURCE_TYPE_NAMES) {
                    try {
                        return (Class<? extends DataSource>) ClassUtils.forName(name, applicationContext.getClassLoader());
                    }
                    catch (Exception ex) {
                        // Swallow and continue
                    }
                }
                return null;
            }
        }.build();
    }
}
